import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {ActivityIndicator,Tools,Button,Modal,Toast } from 'weaver-mobile';
import {Route, withRouter } from 'react-router-dom';
import { RouteLayout,Form } from 'weaver-mobile-page';
import InvoiceInfo from '../reception/InvoiceInfo';
const getLabel = Tools.getLabel;
const operation = Modal.operation;



@withRouter
@inject ('receptionStore')
@observer
class ToOcr extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            fplx:0,
            sreenHeight:0,
        };

    }

    static defaultProps = {
        prefixCls:"fna-reception-type"
    }

    componentDidMount() {
        const {receptionStore} = this.props;
        const {getEquipmentFn} = receptionStore;


        getEquipmentFn();
        
        this.setState({
            sreenHeight:document.documentElement.clientHeight-47
        })
    }

    componentWillUnmount(){
        const {receptionStore} = this.props;
        const {setInvoiceInfo} = receptionStore;
        setInvoiceInfo();
    }


    render() {
        const { receptionStore,prefixCls } = this.props;
        const { ocrInfo,toOcrInvoiceRoute,loading_page,formEnterByHand } = receptionStore;
        const { formParams} = formEnterByHand;

        return (
            <div className={`${prefixCls}`}>
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={loading_page}
                />
                {this.getpage()}
            

                {/* 路由层 */}
                <div>
                    <Route
                        key={toOcrInvoiceRoute.id}
                        path={toOcrInvoiceRoute.path}
                        render={() => {
                            return (
                                <RouteLayout getContainer={() => document.getElementById("root")}>
                                    <div
                                        key="crmListLayout"
                                        className="wm-route-layout"
                                    >
                                        
                                        <InvoiceInfo 
                                            ocrInfo={ocrInfo} 
                                            callBackFn={(value)=>{this.callBackFn(value)}}
                                            callBackUpdata={(value)=>{this.callBackUpdata(value)}}
                                        />
                                    </div>
                                </RouteLayout>
                            )
                        }}
                    /> 
                </div>
            </div>
        )
    }

    getpage = () =>{
        const {receptionStore} = this.props;
        const {formEnterByHand,invoiceInfo} = receptionStore;

        let comment = '';

        comment = [
            <div id="container1" key={'container1'}>
                {invoiceInfo.length > 0 && <div className="title" style={{textAlign:'center',padding:'10px 8px'}}>{getLabel(517369,'请选择发票')}</div>}
                {invoiceInfo.length > 0 ? <div className="invoice-content" style={{height:this.state.sreenHeight-81,overflow:'auto','WebkitOverflowScrolling': 'touch',paddingBottom:'45px'}}>
                    {invoiceInfo.map(items =>{
                        let stateValue = '';
                        if(items.state == '0'){
                            stateValue = '识别失败';
                        }else if(items.state == '1'){
                            stateValue = '识别成功';
                        }else if(items.state == '2'){
                            stateValue = '验票失败';
                        }else if(items.state == '3'){
                            stateValue = '验票成功';
                        }

                        return (
                            <div key={items.invoiceId} onClick={()=>{items.state == '0' ? '' : this.viewInvoice(items.invoiceId,items.newImage)}} className={`fna-ocr-invoiceCSS`}>
                                <div className={`fna-ocr-invoiceCSS-left`}><img src={items.newImage}/></div>
                                <div className={`fna-ocr-invoiceCSS-middle`}>
                                    <div>{items.invoiceNumber}</div>
                                    <div>{items.billingDate}</div>
                                    <div>{items.description}</div>
                                </div>
                                <div className={`fna-ocr-invoiceCSS-right`}>
                                    <div>{items.taxIncludedPrice}</div>
                                    <div className={`state_${items.state}`}>{stateValue}</div>
                                </div>
                            </div>
                        )

                    })}
                </div>:<div className="invoice-noContent" style={{height:this.state.sreenHeight}}></div>}
                

                <div className="invoice-footer invoice-footer-isForm">
                    <Button type="primary" onClick={() => operation(this.getButton())} >{getLabel(514561,'选择发票')}</Button>
                    <Button type="gost" onClick={() => this.doImport()} >{getLabel(18596,'导入')}</Button>
                </div>
                    
                
            </div>
        ]
            
        return comment;
    }

    //获取按钮
    getButton = () =>{
        let btn = [
            { text: ' ',
                style:{background:"no-repeat url('/images/fna/fnaMobile/pz.png') left",backgroundSize:'40px 40px',backgroundPosition: '10px'}, 
                onPress: () => {this.takePicture()} },
            { text: ' ',
                style:{background:"no-repeat url('/images/fna/fnaMobile/zptk.png') left",backgroundSize:'80px 40px',backgroundPosition: '10px'}, 
                onPress: () => {this.photoAlbum()}},
            { text: ' ',
                style:{background:"no-repeat url('/images/fna/fnaMobile/qx.png') left",backgroundSize:'40px 40px',backgroundPosition: '10px'}, 
                onPress: () => {}},
        ];

        return btn;
        
    }

    //导入到form表单
    doImport = () =>{
        const {receptionStore,history,invoiceIds,reset_tjfj} = this.props;
        const {invoiceInfo} = receptionStore;
        let ids = invoiceIds;

        invoiceInfo.map((items,index) =>{
            items['newImage'] = undefined;
            // alert(JSON.stringify(items))
            if(ids == undefined || ids == 'undefined' || ids == ''){
                if(items.invoiceId){
                    ids = items.invoiceId;
                }
            }else{
                if(items.invoiceId){
                    ids += ','+items.invoiceId;
                }
            }
           
        })
        reset_tjfj(ids);
        // console.log('window',window.reset_tjfj)
        history.go(-1)
    } 

    //查看发票
    viewInvoice = (invoiceId,newImage) =>{
        const {receptionStore,history} = this.props;
        const {toOcrInvoiceRoute,setOcrInfo,invoiceInfo} = receptionStore;

        setOcrInfo({
            invoiceId:invoiceId,
            newImage:newImage
        })
        history.push(toOcrInvoiceRoute.path);
    }

    //拍照
    takePicture = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) {Toast.fail(getLabel(525804,'对不起,暂不支持该应用'));return};
        
        let that = this;
        window.em_ssoInit().then(() => {

            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    let localIds = res.localIds; // 返回选定照片的本地ID列表
                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
                                let data = res.localData;
                                that.addImg(data);

                            }
                        });
                    });

                }
            });
        }).catch((res) => {
            alert("连续拍照插件异常,使用原始插件");
            // alert(JSON.stringify(res));
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    }

    //base64数据添加data:image/jpeg;base64,前缀
    addImg = (data) =>{
        let base64PicData = "data:image/jpeg;base64,"+data;
        this.appendDetail(base64PicData);
    }

    appendDetail = (data) =>{
        const {receptionStore} = this.props;
        const {enterInvoiceByOcr} = receptionStore;

        enterInvoiceByOcr({
            operate:'multiCheck',
            fileData:data
        });

    }



    //选照片
    photoAlbum = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) return;
        
        let that = this;
        window.em_ssoInit().then(() => {
            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表
                    
                    // let that = this;
                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
                                var data = res.localData;
                                that.addImg(data);

                            }

                        });
                    });

                }
            });
        }).catch((res) => {
            //alert("连续选照片插件异常,使用原始插件");
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    }

    //回调 函数
    callBackFn = (value) =>{
        const {receptionStore} = this.props;
        const {invoiceInfo,setInvoiceInfo} = receptionStore;
        let _invoiceInfo = [];
        for(let i=0;i<invoiceInfo.length;i++){
            if(invoiceInfo[i].invoiceId == value){
                // _invoiceInfo.splice(i,1);
            }else{
                _invoiceInfo.push(invoiceInfo[i])
            }
        }
        setInvoiceInfo(_invoiceInfo);
    }

    //更新数据
    callBackUpdata = (value) =>{
        const {receptionStore} = this.props;
        const {invoiceInfo,setInvoiceInfo,ocrInfo} = receptionStore;
        // alert(JSON.stringify(value))
        let _invoiceInfo = invoiceInfo;
        for(let i=0;i<_invoiceInfo.length;i++){
            if(_invoiceInfo[i].invoiceId == value.invoiceId){
                _invoiceInfo[i] = value;
                _invoiceInfo[i]['newImage'] = ocrInfo.newImage;
            }
        }
        setInvoiceInfo(_invoiceInfo);
    }


    

}

export default ToOcr;